<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="8em">
      <el-form-item v-hasRole="['superuser']" label="区域代理" prop="agent">
        <el-select v-model="form.agent" placeholder="选择区域代理">
          <el-option
            v-for="item in agentStore.list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="user">
        <el-select v-model="form.user" placeholder="选择用户">
          <el-option
            v-for="item in userProfileStore.list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="联系人名称" prop="contact_name">
        <el-input v-model="form.contact_name" placeholder="请输入联系人名称" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contact_phone">
        <el-input v-model="form.contact_phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="联系人邮箱" prop="contact_email">
        <el-input v-model="form.contact_email" placeholder="请输入联系人邮箱" />
      </el-form-item>
      <el-form-item label="是否正常营业" prop="is_active">
        <el-switch v-model="form.is_active" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="supplierStore.loading.create || supplierStore.loading.update"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineModel } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { useSupplierStoreHook } from "@/store/modules/supplier/supplier";
import { useUserProfileStoreHook } from "@/store/modules/user/profile";
import { useRegionalAgentStoreHook } from "@/store/modules/user/regional-agent";
import { useAgentStoreHook } from "@/store/modules/agent/agent";
import { SupplierForm } from "@/api/supplier/supplier";
import { cloneDeep } from "lodash-es";
import { hasRole } from "@/utils/auth";

const agentStore = useAgentStoreHook();

const supplierStore = useSupplierStoreHook();

const userProfileStore = useUserProfileStoreHook();

const regionalAgentStore = useRegionalAgentStoreHook();

export type FormType = "add" | "edit";

export interface Props {
  type: FormType;
  form?: SupplierForm;
}

const visible = defineModel({ type: Boolean, default: false });

const emits = defineEmits(["confirm"]);

const props = defineProps<Props>();

const formRef = ref();

const selectCityIds = ref<number[]>([]);

const defaultForm: SupplierForm = {
  id: undefined,
  name: "",
  user: "",
  contact_name: "",
  contact_phone: "",
  contact_email: "",
  is_active: true,
  agent: "",
};

const form = reactive<Partial<SupplierForm>>(cloneDeep(defaultForm));

const rules = {
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "change",
    },
  ],
  user: {
    required: true,
    message: "请选择用户",
    trigger: "change",
  },
  contact_name: [
    {
      required: true,
      message: "请输入联系人名称",
      trigger: "change",
    },
  ],
  contact_phone: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "change",
    },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "change",
    },
  ],
  contact_email: [
    {
      required: true,
      message: "请输入联系人邮箱",
      trigger: "change",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱地址",
      trigger: "change",
    },
  ],
};

const title = computed(() => {
  return props.type === "add" ? "新增" : "编辑";
});

watch(visible, async (val) => {
  if (val) {
    if (hasRole(["superuser"])) {
      await agentStore.fetchList({
        page: 1,
        size: 9999,
        search: "",
      });
    }
    await supplierStore.fetchList({ page: 1, size: 9999 });
    await userProfileStore.fetchUserProfileList({ page: 1, size: 9999 });
    await regionalAgentStore.fetchList({ page: 1, size: 9999 });
    if (props.type === "edit") {
      Object.assign(form, props.form);
    }
  } else {
    Object.assign(form, cloneDeep(defaultForm));
    formRef.value.resetFields();
    selectCityIds.value = [];
  }
});

function handleConfirm() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (props.type === "add") {
        await supplierStore.fetchCreate(form);
      } else {
        await supplierStore.fetchUpdate(form);
      }
      visible.value = false;
      emits("confirm");
    }
  });
}
</script>

<style scoped lang="scss"></style>
